package br.com.ufu.traceserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import br.com.ufu.tracemodel.ExtractorControlGui;
import br.com.ufu.tracemodel.TraceFactory;

public class TraceServer {
	private static TraceFactory factory = new TraceFactoryImpl();
    private static ExtractorControlGui controlGui = factory.createControlGui();
    private Map<Thread,TracerThread> tracersMap = new HashMap<Thread,TracerThread>();

    
	public static void main(String[] args) {
		controlGui.getOutputDir();
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(4444);
		} catch (IOException e) {
			System.err
					.println("Nao foi possivel estabelecer a conexao na porta: 4444.");
			System.exit(1);
		}

		Socket clientSocket = null;
		try {
			clientSocket = serverSocket.accept();
		} catch (IOException e) {
			System.err
					.println("Nao foi possivel estabelecer a conexao com o cliente.");
			System.exit(1);
		}

		try {
			PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
					true);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			String inputLine, outputLine;
			TracerProtocol kkp = new TracerProtocol();

			outputLine = kkp.processInput(null);
			out.println(outputLine);

			while ((inputLine = in.readLine()) != null) {
				outputLine = kkp.processInput(inputLine);
				out.println(outputLine);
				if (outputLine.equals("Bye."))
					break;
			}
			out.close();
			in.close();
			clientSocket.close();
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public TracerThread tracer() {
		Thread current = Thread.currentThread();
		TracerThread tracer = null;
		// synchronized(this) {
		tracer = tracersMap.get(current);
		if (null == tracer) {
			tracer = new TracerThread(current, controlGui.getOutputDir(),
					factory);
			tracersMap.put(current, tracer);
			tracer.start();
		}
		// }
		return tracer;
	}
}
